/*
 * Copyright 2012-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot;

import org.springframework.util.ClassUtils;

/**
 * An enumeration of possible types of web application.
 *
 * @author Andy Wilkinson
 * @author Brian Clozel
 * @since 2.0.0
 */
public enum WebApplicationType {

	/**
	 * 该应用程序不应作为web应用程序运行，也不应启动嵌入式web服务器。
	 * The application should not run as a web application and should not start an embedded web server.
	 */
	NONE,

	/**
	 * 该应用程序应作为基于servlet的web应用程序运行，并应启动嵌入式servlet web服务器。
	 * The application should run as a servlet-based web application and should start an embedded servlet web server.
	 */
	SERVLET,

	/**
	 * 该应用程序应作为 响应式web应用程序运行，并应启动嵌入式 响应式web服务器。
	 * The application should run as a reactive web application and should start an embedded reactive web server.
	 */
	REACTIVE;

	private static final String[] SERVLET_INDICATOR_CLASSES = { "javax.servlet.Servlet","org.springframework.web.context.ConfigurableWebApplicationContext" };

	private static final String WEBMVC_INDICATOR_CLASS = "org.springframework.web.servlet.DispatcherServlet";

	private static final String WEBFLUX_INDICATOR_CLASS = "org.springframework.web.reactive.DispatcherHandler";

	private static final String JERSEY_INDICATOR_CLASS = "org.glassfish.jersey.servlet.ServletContainer";

	static WebApplicationType deduceFromClasspath() {

		// 加载下面3个类，第一个存在为 false，第二个不存在为 false，第三个不存在为 true
		boolean present1 = ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null);
		boolean present2 = !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null);
		boolean present3 = !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null);

		// 当只存在 web_flux 时
		if (present1 && present2 && present3) {
			return WebApplicationType.REACTIVE;
		}

		// 当不存在 javax.servlet.Servlet 或者 不存在 org.springframework.web.context.ConfigurableWebApplicationContext 时
		for (String className : SERVLET_INDICATOR_CLASSES) {
			// 不存在时，返回 WebApplicationType.NONE, web 项目都为false
			boolean present4 = !ClassUtils.isPresent(className, null);
			if (present4) {
				return WebApplicationType.NONE;
			}
		}

		return WebApplicationType.SERVLET;
	}

}
